/**
 * 21point
 *
 * outlook@China software studio
 * Copyright (c) 2008-2010. All Rights Reserved.
 * http://www.outlook.com
 */

package org.outlook.test;

import java.util.Stack;

/**
 * function:
 * 
 * @author Watson email: watson.wu@hotmail.com
 * @date 2011
 */
@SuppressWarnings("unchecked")
public class MyStack extends Stack {

	private static final long serialVersionUID = 1L;
	boolean stop = false;
	private Stack stack = new Stack();

	public String toString() {
		return getExpression();
	}

	public boolean isStop() {
		return stop;
	}

	public String getExpression() {
		Object v = stack.pop();
		if (v instanceof Character) {
			String right = getExpression();
			String left = getExpression();
			return "(" + left + v + right + ")";
		}
		return v.toString();
	}

	public void clear() {
		super.clear();
		stack.clear();
		stop = false;
	}

	public Object push(Object v) {
		stack.push(v);
		if (v instanceof Character) {
			Integer v1 = (Integer) pop();
			Integer v2 = (Integer) pop();
			Integer v3 = 0;
			switch ((Character) v) {
			case '+':
				v3 = v2 + v1;
				break;
			case '-':
				v3 = v2 - v1;
				if (v3 < 0)
					stop = true;
				break;
			case '*':
				v3 = v2 * v1;
				break;
			case '/':
				if (v1 != 0 && v2 % v1 == 0) {
					v3 = v2 / v1;
				} else {
					stop = true;
				}
				break;
			}
			return super.push(v3);
		} else {
			return super.push(v);
		}

	}

}
